import React, { useEffect, useState } from "react";
import { Table, Button, Popconfirm, Input, Modal, Space, Form, Tag } from "antd";
import { ColumnsType } from "antd/es/table";
import { createStreamer, deleteStreamer, getStreamers, stopRecording,updateStreamer } from "./ado";
import { useForm } from "antd/es/form/Form"; // 导入 useForm

interface StreamerData {
  id: string;
  name: string;
  liveId: string;
  streaming: string;
  startTime: string;
  priority: number;
}

const StreamerTable: React.FC = () => {
  const [data, setData] = useState<StreamerData[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingStreamer, setEditingStreamer] = useState<StreamerData | null>(null);

  const [form] = useForm(); // 使用 useForm
  async function getData() {
    const data = await getStreamers();
    setData(data);
  }
  // 获取数据
  useEffect(() => {
    getData();
  }, []);
  const RecordingTime: React.FC<{ startTime: string }> = ({ startTime }) => {
    const [time, setTime] = useState(new Date(startTime));
  
    useEffect(() => {
      const timer = setInterval(() => {
        setTime(new Date());
      }, 1000);
  
      return () => clearInterval(timer);
    }, []);
  
    const duration = time.getTime() - new Date(startTime).getTime();
    const seconds = Math.floor(duration / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
  
    return (
      <Tag color="red">
        {`${hours}:${minutes % 60}:${seconds % 60}`}
      </Tag>
    );
  };
  
  // 在 columns 定义中修改 render 函数
    
  // 表格列配置
  const columns: ColumnsType<StreamerData> = [
    {
      title: 'Name',
      dataIndex: 'name',
    },
    {
      title: 'Live ID',
      dataIndex: 'liveId',
    }, {
      title: 'Status',
      dataIndex: 'streaming',
      render: (streaming: string, record:StreamerData) => {
        if (streaming === 'recording') {
          return <RecordingTime startTime={record.startTime} />;
        } else if (streaming === 'live') {
          return (
            <Tag color="green">
              Live
            </Tag>
          );
        }
        return (
          <Tag color="gray">
            Offline
          </Tag>
        );
      }
    },{
      title: 'Priority',
      dataIndex: 'priority',
    }
    ,
    {
      title: 'Action',
      render: (_text, record) => (
        <Space size="middle">
          <Button onClick={() => handleEdit(record)}>Edit</Button>
          <Popconfirm
            title="Are you sure to delete?"
            onConfirm={async () => {
              await deleteStreamer(record.id);
            }

            }
          >
            <Button danger>Delete</Button>
          </Popconfirm>
          {record.streaming==='recording'?<Button
          onClick={async () => {
            await stopRecording(record.liveId);
            getData();
          }}
          >stop</Button>:null}
        </Space>
      ),
    },
  ];

  const handleDelete = (id: string) => {
    // 调用 API 删除数据（这里暂时只是删除本地数据，实际应用中需要调用后端接口）
    setData(prevData => prevData.filter(item => item.id !== id));
  };

  const handleEdit = (streamer: StreamerData) => {
    setEditingStreamer(streamer);
    form.setFieldsValue({
      name: streamer.name,
      liveId: streamer.liveId,
      priority: streamer.priority
    });
    setIsModalVisible(true);
  };
  
  
  const handleModalOk = async () => {
    try {
      // 获取表单数据
      const values = await form.validateFields();

      // 确保输入有效
      if (!values.name || !values.liveId) {
        return; // 输入不完整时不进行操作
      }

      if (editingStreamer) {
        // 如果是编辑现有主播
        await updateStreamer(editingStreamer.id, values.name, values.liveId, values.priority);
      } else {
        // 如果是创建新主播
        await createStreamer(values.name, values.liveId, values.priority);
      }
      
      // 更新表格数据
      getData();
      // 关闭 modal
      setIsModalVisible(false);
      setEditingStreamer(null);
      form.resetFields(); // 重置表单
    } catch (error) {
      // 错误处理
      console.error('Failed to save streamer:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setEditingStreamer(null);
    form.resetFields(); // 重置表单
  };

  const handleAdd = () => {
    // 打开 modal 以添加新 streamer
    setIsModalVisible(true);
    setEditingStreamer(null);
    form.resetFields(); // 重置表单
  };

  return (
    <div>
      <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
        Add Streamer
      </Button>
      <Table columns={columns} dataSource={data} rowKey="id" />
      <Modal
        title={editingStreamer ? 'Edit Streamer' : 'Add Streamer'}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="Name"
            name="name"
            rules={[{ required: true, message: 'Name is required' }]}
          >
            <Input placeholder="Name" />
          </Form.Item>
          <Form.Item
            label="Live ID"
            name="liveId"
            rules={[{ required: true, message: 'Live ID is required' }]}
          >
            <Input placeholder="Live ID" />
          </Form.Item>
          <Form.Item 
            label="Priority"
            name="priority"       
          >
             <Input type="number"/>   
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StreamerTable;
